/** ele admin theme util license by http://eleadmin.com */
import { generate } from '@ant-design/colors';

/**
 * 切换主题色
 * @param color 颜色值
 * @param dark 是否暗黑模式
 */
export function changeColor(color, dark) {
  const id = `ele-admin-theme-var`;
  const elem = document.getElementById(id);
  if (elem && elem.parentNode) {
    elem.parentNode.removeChild(elem);
  }
  if (color) {
    const colors = generate(color, dark ? { theme: 'dark' } : {});
    const elem = document.createElement('style');
    const clazz = dark ? '.ele-admin-theme-dark' : ':root';
    elem.id = id;
    elem.setAttribute('type', 'text/css');
    const colorVar = colors
      .map((c, i) => `--color-primary-${i + 1}:${c};`)
      .join('');
    elem.innerHTML = `${clazz}{--color-primary:${color};${colorVar}}`;
    document.head.appendChild(elem);
  }
  if (dark) {
    document.body.classList.add('ele-admin-theme-dark');
  } else {
    document.body.classList.remove('ele-admin-theme-dark');
  }
}

/**
 * 切换主题文件
 * @param name 主题名称
 * @param dark 是否是暗黑模式
 * @param importer 加载器
 * @returns {Promise<>}
 */
export function changeTheme(name, dark, importer) {
  // 对应的css文件名
  const css_name = dark ? (name ? name + '-dark' : 'dark') : name;
  return new Promise((resolve, reject) => {
    if (!css_name) {
      removeTheme(); // 移除上次的主题
      return resolve();
    }
    // 主题css的js模块是否已加载过
    const oldElem = document.head.querySelector(`#ele-theme-${css_name}-js`);
    if (oldElem) {
      removeTheme(); // 移除上次的主题
      const elem = document.createElement('link');
      elem.id = `ele-theme-${css_name}`;
      elem.setAttribute('type', 'text/css');
      elem.setAttribute('rel', 'stylesheet');
      elem.setAttribute('href', oldElem.getAttribute('ele-css'));
      document.head.appendChild(elem);
      return resolve();
    }
    // 把head下面相关元素标记为非主题元素
    const nid = ':not([id^="ele-theme-"])';
    const sel = `style${nid},link${nid},script${nid}`;
    [].forEach.call(document.head.querySelectorAll(sel), (elem) => {
      if (!elem.getAttribute('ele-theme')) {
        elem.setAttribute('ele-theme', 'no');
      }
    });
    // 加载主题css模块
    importer(css_name)
      .then(() => {
        removeTheme(); // 移除上次的主题
        // 获取import之后的主题标签
        let elem = document.head.querySelectorAll(
          'style:not([ele-theme="no"])'
        );
        elem = elem.length ? elem[elem.length - 1] : null;
        if (!elem) {
          // 可能是style标签也可能是link标签
          elem = document.head.querySelectorAll('link:not([ele-theme="no"])');
          elem = elem.length ? elem[elem.length - 1] : null;
          if (!elem) {
            return reject(new Error('theme element not found'));
          }
          // 再找到对应的主题js模块的标签
          const href = elem.getAttribute('href');
          const uuid = href.substring(
            href.indexOf('chunk-'),
            href.indexOf('.')
          );
          const qs = `script[src^="/js/${uuid}"]:not([ele-theme="no"])`;
          const node = document.head.querySelectorAll(qs);
          if (node.length) {
            node[node.length - 1].id = `ele-theme-${css_name}-js`;
            // 记录css地址
            node[node.length - 1].setAttribute('ele-css', href);
          }
        }
        elem.id = `ele-theme-${css_name}`;
        return resolve();
      })
      .catch((e) => {
        reject(e);
      });
  });
}

/**
 * 移除主题
 */
function removeTheme() {
  const sel = 'style[id^="ele-theme-"],link[id^="ele-theme-"]';
  [].forEach.call(document.head.querySelectorAll(sel), (elem) => {
    elem.parentNode.removeChild(elem);
  });
}
